<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="账号信息"></u-navbar> -->
		<free-list-item title="我的头像" :showRight="false" :showLeftIcon="false" @click="updates('navatar')">
		<u-image slot="right" :src="getFullImageUrl(ifdUser.avatar)"  border-radius= "100rpx"
			style="width: 60px; height: 60px; margin-right: 10px;" @error="handleImageError"
			></u-image>
		
		</free-list-item>
		<free-list-item title="名字" :showRight="false" :showRightIcons="false" :showLeftIcon="false">
			<text slot="right" class="font-14 text-muted">{{ifdUser.enterpriseName}}</text>
		</free-list-item>
		<free-list-item title="绑定手机号" :showRight="false" :showLeftIcon="false" @click="updates('bindPhone')">
			<text slot="right" class="font-14 text-muted ursrRight">{{ifdUser.phone}}</text>
		</free-list-item>

		<free-list-item title="登录密码" :showRight="false" :showLeftIcon="false" @click="updates('Password')">
			<text slot="right" class="font-14 text-muted ursrRight">{{maskedPassword}}</text>
		</free-list-item>

		<!-- 修改名字|修改微信号 弹框-->
		<free-confirm ref="confirm" :title="confirmTitle">
			<view class="pl-3">
				<u-form :model="form" ref="uForm">
					<u-form-item :required="true" label="原密码" label-width="120" prop="oldPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入原密码" v-model="form.oldPassword" input-align="right" />
					</u-form-item>
					<u-form-item :required="true" label="新密码" label-width="120" prop="newPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入新密码" v-model="form.newPassword" input-align="right" />
					</u-form-item>
					<u-form-item :required="true" label="确认新密码" label-width="180" prop="confirmPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请再次输入密码" v-model="form.confirmPassword" input-align="right" />
					</u-form-item>
				</u-form>
					<view class="font-12 mt-1" style="color: red;">由英文、数字、特殊字符中的至少2种组成，不少于6位</view>
			</view>
		</free-confirm>
		<!-- 修改手机号码 弹框-->
		<free-confirm ref="confirmShow" :title="confirmPhomTitle">
			<view class="pl-3">
				<u-form :model="form">
					<u-form-item :required="true" label="手机号码" label-width="180" prop="phone">
						<u-input class="mr-3 " maxlength="11" placeholder="请输入所绑定的手机号" v-model="code.phone" input-align="right" />
					</u-form-item>
					<u-form-item :required="true"label="验证码" label-width="180" prop="captcha">
						<u-input class="mr-3 " placeholder="请输入验证码" v-model="code.captcha" input-align="right" />
						<u-button size="mini" slot="right" type="warning" @click="getCode">{{codeText}}</u-button>
					</u-form-item>
				</u-form>
				<u-toast ref="uToast"></u-toast>
				<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode"
					@change="codeChange"></u-verification-code>
			</view>
		</free-confirm>
	</view>
</template>

<script>
	import freeListItem from '@/components/free-ui/free-list-item.vue'
	import freeAvater from '@/components/free-ui/free-avater.vue'
	import freeDivider from '@/components/free-ui/free-divider.vue'
	import freeConfirm from '@/components/free-ui/free-confirm.vue'
	import $H from '@/common/free-lib/request.js'
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	export default {
		components: {
			freeListItem,
			freeAvater,
			freeDivider,
			freeConfirm,
		},
		data() {
			return {
				ifdUser: '',
				codeText: '',
				confirmText: '',
				confirmType: '',
				mobile: '', // 手机号
				seconds: 60,
				userInfo: '',
				//密码
				oldPwd: '',
				newPwd: '',
				confirmNewPwd: '',
				form: {
					oldPassword: '', // 原密码
					newPassword: '', // 新密码
					confirmPassword: '', // 确认密码
				},
				ifdUser: '',
				labelStyle: {
					paddingLeft: '13px',
					width: '130px'
				},
				code: {
					phone: '',
					captcha: ''
				}

			}
		},
		onShow() {
			let store = uni.getStorageSync('userInfo')
			if (store) {
				this.loginStatus = true
				this.userInfo = store
			}
		},
		onLoad(options) {
			const id = options.id;
			this.NewUser(id);
		},
		computed: {
			confirmTitle() {
				return this.confirmType == 'username' ? '修改密码' : '修改密码'
			},
			confirmPhomTitle() {
				return this.confirmType == 'username' ? '更换手机号' : '更换手机号'
			},
			placeholder() {
				return this.confirmType == 'username' ? '输入账号' : '输入名称'
			},
			maskedPassword() {
				// 如果 this.ifdUser 不存在或者 username 为空，则返回空字符串
				if (!this.ifdUser || !this.ifdUser.username) {
					return '';
				}
				// 否则将密码替换为星号
				return this.ifdUser.username.replace(/./g, "*");
			}
		},
		methods: {
			codeChange(text) {
				this.codeText = text
			},
			handleImageError() {
				uni.showToast({
					title: '图片格式不支持jpeg，请重新上传',
					icon: 'none',
					duration: 4000
				});
			
			},
			// 拼接图片方法
			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			validatePhoneNumber(phoneNumber) {
				var regex = /^1\d{10}$/;
				return regex.test(phoneNumber);
			},
			getCode() {
				if (this.getCodeisWaiting) {
					return;
				}
				
				// 验证手机号码是否为空
				if (!this.code.phone) {
					uni.showToast({
						title: "请输入手机号码",
						icon: 'none'
					});
					return;
				}
				// 隐藏键盘
				uni.hideKeyboard();
				this.getCodeText = "发送中...";
				this.getCodeisWaiting = true;
				let o = {
					phone: this.code.phone
				};

				// 发送请求获取验证码
				$H.post('/brand/user/down/editePhoneSendSms', o,{
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
					}
				})
					.then(res => {
						if(!res.success||res.code!=200){
							uni.showToast({
								title: res.message||'获取验证码失败',
								icon: 'error',
								duration: 4000
							});
							return;
						}
						if (this.$refs.uCode.canGetCode) {
							if (!this.validatePhoneNumber(this.code.phone)) {
								uni.showToast({
									title: "手机号码格式错误",
									icon: "error",
									duration: 4000
								});
								return;
							}
							uni.showLoading({
								title: '正在获取验证码'
							});
							setTimeout(() => {
								uni.hideLoading();
								this.$refs.uCode.start();
							}, 2000);
						} else {
							this.$u.toast('倒计时结束后再发送');
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			end() {
				this.$u.toast('倒计时结束');
				this.getCodeisWaiting = false;
				this.codeText = '重新获取';
			},
			start() {
				this.$u.toast('倒计时开始');
			},
			editePhone(id) {
				let o = {
					...this.code,
					id: this.id
				};
				$H.post('/brand/user/down/editePhone', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 4000
							});
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 4000
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			/**end  验证码**/

			// 点击事件
			updates(key) {
				const this_ = this;
				switch (key) {
					case 'navatar':
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							success: (res) => {
								// 上传
								this_.avatars(res.tempFilePaths[0]);
							}
						})
						break;
					case 'bindPhone':
						// 处理绑定手机号码逻辑，弹起弹框
						this_.confirmType = 'bindPhone';
						this_.confirmText = this_.ifdUser.bindPhone;
						this_.$refs.confirmShow.show((close) => {
							this_.editePhone();
							this_.phoneData()
							if (this_.confirmText === '') {
								return uni.showToast({
									title: "不能为空",
									icon: 'none',
									duration: 4000
								});
							}
							this_.ifdUser.bindPhone = this_.confirmText;
							// close();
						});
						break;
					case 'Password':
						this_.$refs.confirm.show(function(close) {
							if (!this_.form.oldPassword || !this_.form.newPassword || !this_.form.confirmPassword) {
								uni.showToast({
									title: "请填写正确密码",
									icon: 'none',
									duration: 4000
								})
								return;
							}
							
							if (this_.form.newPassword != this_.form.confirmPassword) {
								uni.showToast({
									title: "两次密码不一致",
									icon: 'none',
									duration: 4000
								})
								return;
							}
							this_.changePassword();
							close();
						});
					default:
						break;
				}
			},
			phoneData() {
				// 清空表单数据
				this.code.phone = '';
				this.code.captcha = '';
			},
			/**start  修改密码**/
			changePassword(id) {
				let o = {
					...this.form,
					id: this.id
				};
				$H.post('/brand/user/down/editPassword', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 4000
							});
							// 关闭弹框并清空数据
							this.clearData();
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 4000
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none',
							duration: 4000
						});
					});
			},
			clearData() {
				// 清空表单数据
				this.form.confirmPassword = '';
				this.form.newPassword = '';
				this.form.oldPassword = '';
			},
			/** end 修改密码**/

			// 上传头像
			avatars(filePath) {
			    $H.upload('/sys/common/upload', {
			        filePath: filePath
			    }, {}).then((avatar) => {
			        if (avatar && avatar.message) {
			            $H.post('/brand/user/down/editAvatar', {
			                avatar: avatar.message // 将 avatar 传递给 editAvatar 方法
			            }, {
			                header: {
			                    'Content-Type': 'application/x-www-form-urlencoded'
			                }
			            }).then((res) => {
			                if (res.code === 200) {
			                    uni.showToast({
			                        title: res.message,
			                        icon: 'none',
									duration: 4000
			                    });
			                    this.NewUser(this.id);
			                } else {
			                    uni.showToast({
			                        title: res.message,
			                        icon: 'none',
									duration: 4000
			                    });
			                }
			                // 在这里处理 editAvatar 方法返回的数据
			            }).catch((error) => {
			                console.error('编辑头像失败', error);
			                uni.showToast({
			                    title: '编辑头像失败',
			                    icon: 'none'
			                });
			            });
			        } else {
			            uni.showToast({
			                title: '上传失败,图片限制不能超过4MB',
			                icon: 'none',
							duration: 4000 
			            });
			        }
			    }).catch((error) => {
			        console.error('上传失败', error);
			        uni.showToast({
			            title: '上传失败',
			            icon: 'none'
			        });
			    });
			},
			openCode() {
				uni.navigateTo({
					url: '/pages/my/code/code',
				})
			},
			NewUser(id) {
				$H.get('/brand/user/queryById', {
					id: id
				}, {}).then(res => {
					this.ifdUser = res.result
					this.id = res.result.id
				}).catch(error => {
					uni.showToast({
						title: "网络错误，请稍后再试",
						icon: 'none'
					});
				});
			},
		},
	}
</script>

<style></style>